package com.gitee.huanminabc.fastboot.orm.stage;

import com.alibaba.fastjson.JSONObject;
import com.gitee.huanminabc.jcommon.str.StringUtil;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.load.stage.prestage.AppLoadPreStage;
import com.gitee.huanminabc.jlambda_sql.jdbc.JdbcCommand;
import com.gitee.huanminabc.jlambda_sql.jdbc.JdbcDataSource;
import com.gitee.huanminabc.jlambda_sql.jdbc.JdbcManage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Properties;

/**
 * 简要描述
 *
 * @Author: huanmin
 * @Date: 2025/4/5 19:43
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
@Slf4j
public class OrmDatasourceListLoadStage implements AppLoadPreStage {
    @Override
    public void run() {
        try {
            JSONObject jsonObject = AppContext.appConfigMap.getJSONObject("datasourceList");
            if (jsonObject == null) {
                log.error("缺少数据源相关配置 datasourceList");
                System.exit(1);
            }
            String defaultKey = jsonObject.getString("default");
            if (StringUtil.isEmpty(defaultKey)) {
                throw new RuntimeException("datasourceList default key is null");
            }
            JdbcCommand.sqlLogPrintOpen = jsonObject.getBooleanValue("sqlLogPrintOpen");
            JdbcManage.setDefaultDbKey(defaultKey);
            for (Map.Entry<String, Object> stringObjectEntry : jsonObject.entrySet()) {
                String key = stringObjectEntry.getKey();
                if (key.equals("default") || key.equals("sqlLogPrintOpen")) {
                    continue;
                }
                JSONObject prop = (JSONObject) stringObjectEntry.getValue();
                //兼容url
                prop.put("jdbcUrl", prop.getString("url"));
                //刪除
                prop.remove("url");
                Properties properties = new Properties();
                properties.putAll(prop);

                HikariConfig hikariConfig = new HikariConfig(properties);
                DataSource dataSource = new HikariDataSource(hikariConfig);
                JdbcDataSource.addDataSource(key, dataSource);
            }
        } catch (Exception e) {
            log.error("OrmDatasourceListLoadStage load error", e);
            System.exit(1);
        } finally {
            log.debug("OrmDatasourceListLoadStage load success");
        }
    }
}
